package pers.hl.module_main.search

import android.os.Bundle
import android.util.Log
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ObjectUtils
import kotlinx.android.synthetic.main.include_toolbar_search.*
import pers.hl.common.base.BaseVBVMActivity
import pers.hl.common.base.ext.showMessage
import pers.hl.common.ui.CommonTextWatcher
import pers.hl.lib_global.common.Const.RequestParam.DEFAULT_PAGE_NUM
import pers.hl.module_main.common.IViewStatus
import pers.hl.module_main.databinding.ActivitySearchBinding

class SearchActivity : BaseVBVMActivity<ActivitySearchBinding, SearchViewModel>(), IViewStatus {

    lateinit var bookAdapter: BookAdapter

    private var curPageNum = DEFAULT_PAGE_NUM

    private var pageCount = 0

    override fun initView(savedInstanceState: Bundle?) {
        initRefresh()
        initToolBar()
        initRvAdapter()
    }

    private fun initRefresh() {
        mBinding.apply {
            refreshLayout.setOnRefreshListener {
                Log.e(TAG, "setOnRefreshListener")
                resetPageNum()
                doSearch()
            }
            refreshLayout.setOnLoadMoreListener {
                if (pageCount != 0 && pageCount == curPageNum + 1) {
                    LogUtils.d(TAG, "当前已加载到第${curPageNum}页, 不再加载更多")
                    return@setOnLoadMoreListener
                }
                doSearch(true)
            }
        }
    }

    private fun initToolBar() {
        mBinding.apply {
            ivLeft.setOnClickListener {
                finish()
            }
            etSearch.imeOptions = EditorInfo.IME_ACTION_SEARCH
            etSearch.addTextChangedListener(object : CommonTextWatcher(etSearch) {
                override fun textChanged(view: EditText, text: String) {

                }
            })
            etSearch.setOnEditorActionListener { v, actionId, event ->
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    doSearch()
                }
                false
            }
            ivSearch.setOnClickListener {
                doSearch()
            }
        }

    }

    private fun doSearch() {
        doSearch(false)
    }

    private fun doSearch(loadMore: Boolean) {
        val content = etSearch.text.toString()
        if (content.isEmpty()) {
            showMessage("搜索关键字不能为空")
            return
        }
        if (!loadMore) {
            resetPageNum()
        } else {
            curPageNum++
        }
        LogUtils.d(TAG, "加载更多：$loadMore 当前请求第${curPageNum}页")
        mViewModel.search(content, curPageNum).observe(this, Observer {
            if (loadMore) {

                LogUtils.d(TAG, "请求返回 加载更多：$loadMore 当前请求第${curPageNum}页")
                bookAdapter.addData(it)
                finishLoadMore()
            } else {
                // fixme 这里有问题 加载更多不应该回调到这里 loadMore 变量变成了false 是否与线程有关
                LogUtils.d(TAG, "请求返回  加载更多：$loadMore 当前请求第${curPageNum}页")
                if (ObjectUtils.isEmpty(it)) {
                    showEmptyView()
                } else {
                    bookAdapter.setList(it)
                }

            }

        })
    }

    private fun initRvAdapter() {
        bookAdapter = BookAdapter(mutableListOf())
        mBinding.apply {
            rvSearch.layoutManager =
                LinearLayoutManager(this@SearchActivity, LinearLayoutManager.VERTICAL, false)
            rvSearch.adapter = bookAdapter
            bookAdapter.notifyDataSetChanged()
        }

    }

    override fun initData(savedInstanceState: Bundle?) {

    }

    private fun resetPageNum() {
        curPageNum = DEFAULT_PAGE_NUM
    }

    override fun showLoading() {
        mBinding.refreshLayout.autoRefreshAnimationOnly()
    }

    override fun hideLoading() {
        mBinding.refreshLayout.finishRefresh()
        finishLoadMore()

    }

    override fun loadMore() {
        mBinding.refreshLayout.autoLoadMoreAnimationOnly()
    }

    override fun finishLoadMore() {
        mBinding.refreshLayout.finishLoadMore()
    }

    override fun showEmptyView() {
        if (bookAdapter.data.isNotEmpty()) {
            bookAdapter.data.clear()
            bookAdapter.notifyDataSetChanged()
        }
        bookAdapter.setEmptyView()
    }

    override fun showErrorView() {

    }
}